package core.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author songduk park
 * 
 */
public class CookieUtil {

	/** Find a cookie by name; return first found */
	public Cookie getCookie(HttpServletRequest request, String name) {
		if (name == null)
			throw new IllegalArgumentException("cookie name is null");

		Cookie[] cookies = request.getCookies();

		if (cookies == null)
			return null;

		for (Cookie cookie : cookies) {
			if (name.equals(cookie.getName())) {
				return cookie;
			}
		}

		return null;
	}

	public void printAllCookie(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();

		if (cookies == null)
			return;

		for (Cookie cookie : cookies) {
			System.out.println(cookie.getName() + " : " + cookie.getValue());
		}
	}

	/** Set a cookie by name */
	public void setCookieValue(HttpServletResponse response, String name,
			String value) {
		Cookie c = new Cookie(name, value);

		c.setMaxAge(3 * 30 * 24 * 60 * 60);
		c.setPath("/");

		response.addCookie(c);
	}

	public void deleteCookie(HttpServletResponse response, String name) {
		Cookie c = new Cookie(name, "false");

		c.setMaxAge(0); // An age of 0 is defined to mean "delete cookie"
		c.setPath("/"); // for all subdirs

		response.addCookie(c);
	}
}
